import tool from '../modules/tool'
const controls = tool.cControls

import { useStore } from '../modules/store'
const store = useStore()

export default async (reloadPage, handleError) => {

    const left = {
        data: [],
        async init() {
            let re = await tool.requestData('/category/getList', {
                withPaper: true
            }, {}, 'get')
            if (re.status) {
                for (let i = 0; i < re.data.length; i++) {
                    re.data[i].label = re.data[i].name
                    re.data[i].children = []
                    for (let i1 = 0; i1 < re.data[i].paperList.length; i1++) {
                        re.data[i].children.push({
                            label: re.data[i].paperList[i1].name,
                            categoryId: re.data[i].id,
                            paperId: re.data[i].paperList[i1].id,
                            paperName: re.data[i].paperList[i1].name,
                            categoryName: re.data[i].name
                        })
                    }
                }
                this.data = re.data
            } else {
                throw re.content
            }
        }
    }

    await left.init()

    const paper = {
        list: [],
        paperName: undefined,
        categoryName: undefined,
        paperId: undefined,
        categoryId: undefined,
        async get(paperId, paperName, categoryName, categoryId) {
            let re = await tool.requestData('/paper/getQuestionList', {
                paperId
            }, {}, 'get')
            if (re.status) {
                this.paperName = paperName
                this.categoryName = categoryName
                this.categoryId = categoryId
                this.paperId = paperId
                this.list = re.data
            } else {
                throw re.content
            }
        },
        mSelect: controls.mSelectObject(),
        resetNum() {
            for (let i = 0; i < this.list.length; i++) {
                this.list[i].index = i + 1
            }
            reloadPage()
        },
        moveItem(arrIndex, toArrIndex) {
            let item = tool.deepCopyObject(this.list[arrIndex])
            this.list = [...this.list.slice(0, arrIndex), ...this.list.slice(arrIndex + 1)]
            if (toArrIndex > arrIndex) {
                toArrIndex--
                this.list = [...this.list.slice(0, toArrIndex + 1), item, ...this.list.slice(toArrIndex + 1)]
            } else {
                this.list = [...this.list.slice(0, toArrIndex), item, ...this.list.slice(toArrIndex)]
            }
            this.resetNum()
            reloadPage()
        },
        deleteItem(index) {
            this.list = this.list.filter(item => item.index !== index)
            this.resetNum()
        }
    }

    const refresh = async () => {
        return {
            type: 1,
            left: {
                title: '试卷列表',
                list: left.data,
                props: {
                    children: 'children',
                    label: 'label',
                },
                async callBack(e) {
                    if (!e.children) {
                        if (paper.paperName !== undefined) {
                            try {
                                await new Promise((resolve, reject) => {
                                    store.showModal2('提示', `此操作会直接关闭您当前正在编辑的试卷，是否继续？`, () => {
                                        resolve()
                                        store.hideModal2()
                                    }, true, () => reject())
                                })
                            } catch (error) {
                                store.hideModal2()
                                return
                            }
                        }
                        tool.flow(async () => {
                            paper.list = []
                            paper.paperName = undefined
                            paper.mSelect.removeAll()
                            reloadPage()
                            await tool.wait(0.01)
                            await paper.get(e.paperId, e.paperName, e.categoryName, e.categoryId)
                            reloadPage()
                        }, err => tool.toast.error(`${err}`))
                    }
                }
            },
            main: {
                tab: [
                    ...(() => {
                        if (paper.paperName === undefined) return []
                        return [
                            {
                                title: `${paper.categoryName} - ${paper.paperName}`,
                                bottomControls: [],
                                topControls: [
                                    controls.button({
                                        title: '保存',
                                        leftIcon: 'save',
                                        type: 'primary',
                                        async callBack() {
                                            await tool.flow(async () => {
                                                let re_upload = await tool.uploadFile('/file/upload', await (async () => {
                                                    let a = new FormData()
                                                    a.append('file', (await tool.createVirtualFile(JSON.stringify(paper.list))).file)
                                                    return a
                                                })())
                                                try {
                                                    re_upload = JSON.parse(re_upload)
                                                } catch (error) {

                                                }
                                                if (re_upload.status) {

                                                } else {
                                                    throw '上传失败'
                                                }
                                                let re = await tool.requestData('/paper/updateQuestionList', {}, {
                                                    paperId: paper.paperId,
                                                    categoryId: paper.categoryId,
                                                    fileName: re_upload.data
                                                })
                                                if (re.status) {
                                                    tool.toast.success('成功')
                                                    await paper.get(paper.paperId, paper.paperName, paper.categoryName, paper.categoryId)
                                                    reloadPage()
                                                } else {
                                                    throw re.content
                                                }
                                            }, err => tool.toast.error(`${err}`))
                                        }
                                    }),
                                    controls.button({
                                        title: '删除本试卷',
                                        leftIcon: '删除',
                                        type: 'danger',
                                        async callBack() {
                                            store.showModal2('提示', '是否删除本试卷？', async () => {
                                                tool.flow(async () => {
                                                    let re = await tool.requestData('/paper/delete', {}, {
                                                        paperId: paper.paperId
                                                    }, 'post')
                                                    if (re.status) {
                                                        await left.init()
                                                        paper.paperId = undefined
                                                        paper.paperName = undefined
                                                        reloadPage()
                                                    } else {
                                                        throw re.content
                                                    }
                                                }, err => tool.toast.error(`${err}`))
                                            }, true, () => store.hideModal2())
                                        }
                                    }),
                                    controls.button({
                                        title: '添加题目',
                                        leftIcon: 'add',
                                        async callBack() {
                                            tool.forms.question.add((value, fm) => {
                                                value.id = new Date()
                                                value.new = true
                                                paper.list = [value, ...paper.list]
                                                paper.resetNum()
                                                reloadPage()
                                                store.hideFormDialog()
                                            }, () => store.hideFormDialog())
                                        }
                                    }),
                                    controls.button({
                                        title: '回到顶部',
                                        leftIcon: 'top',
                                        async callBack() {
                                            let data = tool.deepCopyObject(paper.list)
                                            paper.list = []
                                            reloadPage()
                                            await tool.wait(0.01)
                                            paper.list = data
                                            reloadPage()
                                        }
                                    }),
                                    ...controls.mSelectControls(
                                        () => paper.mSelect.getList(),
                                        (e) => paper.mSelect.setList(e),
                                        () => reloadPage(),
                                        [
                                            {
                                                title: '删除已选',
                                                leftIcon: '删除',
                                                callBack() {
                                                    store.showModal2('提示', '是否删除已选题目？', () => {
                                                        paper.mSelect.getList().forEach(item => {
                                                            paper.list = paper.list.filter(itm => itm.id !== item)
                                                        })
                                                        paper.resetNum()
                                                        paper.mSelect.removeAll()
                                                        store.hideModal2()
                                                        reloadPage()
                                                    }, true, () => store.hideModal2())
                                                }
                                            }
                                        ],
                                        () => tool.selectValueOfObjectByKey(paper.list, 'id')
                                    )
                                ],
                                data: {
                                    type: 'list',
                                    enableSelect: true,
                                    list: (() => {
                                        let re = []
                                        paper.list.forEach(item => {
                                            item.haveImg = item.img ? '有' : '无'
                                            item.modified_read = item.modified ? '已完善' : '未完善'
                                            re.push({
                                                title: `${item.index}. ${item.stems}`,
                                                content: tool.generateHTML(
                                                    [
                                                        {
                                                            field: 'type', title: '类型'
                                                        },
                                                        {
                                                            field: 'haveImg', title: '图片'
                                                        },
                                                        ...(() => {
                                                            if (item.type === '选择') {
                                                                return [
                                                                    {
                                                                        field: item.optionAType === 'image' ? 'optionAType' : 'optionA', title: '选项A'
                                                                    },
                                                                    {
                                                                        field: item.optionBType === 'image' ? 'optionBType' : 'optionB', title: '选项B'
                                                                    },
                                                                    {
                                                                        field: item.optionCType === 'image' ? 'optionCType' : 'optionC', title: '选项C'
                                                                    },
                                                                    {
                                                                        field: item.optionDType === 'image' ? 'optionDType' : 'optionD', title: '选项D'
                                                                    },
                                                                ]
                                                            }
                                                            return []
                                                        })(),
                                                        {
                                                            field: 'answer', title: '答案'
                                                        },
                                                        {
                                                            field: 'analysis', title: '解析'
                                                        },
                                                        {
                                                            field: 'keywords', title: '关键词'
                                                        },
                                                        {
                                                            field: 'modified_read', title: 'AI完善'
                                                        },
                                                    ],
                                                    item
                                                ),
                                                operations: [
                                                    {
                                                        icon: 'edit',
                                                        tip: '编辑',
                                                        op: 'edit'
                                                    },
                                                    {
                                                        icon: '删除',
                                                        tip: '删除',
                                                        op: 'delete'
                                                    },
                                                    {
                                                        icon: 'index',
                                                        tip: '修改序号',
                                                        op: 'changeIndex'
                                                    },
                                                    ...(() => {
                                                        if (item.index === 1) return []
                                                        return [
                                                            {
                                                                icon: 'top',
                                                                tip: '向上移动',
                                                                op: 'up'
                                                            }
                                                        ]
                                                    })(),
                                                    ...(() => {
                                                        if (item.index === paper.list.length) return []
                                                        return [
                                                            {
                                                                icon: 'bottom',
                                                                tip: '向下移动',
                                                                op: 'down'
                                                            }
                                                        ]
                                                    })(),
                                                ],
                                                item,
                                                selected: paper.mSelect.is(item.id)
                                            })
                                        })
                                        return re
                                    })(),
                                    callBack(e) {
                                        console.log(e)
                                        if (e.op === 'select') {
                                            paper.mSelect.add(e.item.item.id)
                                        }
                                        if (e.op === 'unselect') {
                                            paper.mSelect.remove(e.item.item.id)
                                        }
                                        if (e.op === 'up') {
                                            paper.moveItem(e.item.item.index - 1, e.item.item.index - 2)
                                        }
                                        if (e.op === 'down') {
                                            paper.moveItem(e.item.item.index - 1, e.item.item.index)
                                        }
                                        if (e.op === 'delete') {
                                            store.showModal2('提示', `是否删除问题 ${e.item.item.index} ？`, () => {
                                                paper.deleteItem(e.item.item.index)
                                                store.hideModal2()
                                                paper.mSelect.remove(e.item.item.id)
                                                reloadPage()
                                            }, true, () => store.hideModal2())
                                        }
                                        if (e.op === 'edit' || e.op === 'titleClick') {
                                            tool.forms.question.edit(e.item.item, (value, fm) => {
                                                if (Object.keys(value).length === 0) {
                                                    store.hideFormDialog()
                                                    return
                                                }
                                                for (let i = 0; i < paper.list.length; i++) {
                                                    if (paper.list[i].index === value.index) {
                                                        paper.list[i] = value
                                                        break
                                                    }
                                                }
                                                store.hideFormDialog()
                                                reloadPage()
                                            })
                                        }
                                        if (e.op === 'changeIndex') {
                                            store.showFormDialog('修改序号', [], [
                                                {
                                                    field: 'index',
                                                    title: '新的序号'
                                                }
                                            ], { index: e.item.item.index }, false, (itm) => {
                                                console.log(itm)
                                                if (Object.keys(itm).length === 0) {
                                                    store.hideFormDialog()
                                                    return
                                                }
                                                itm.index = parseInt(itm.index)
                                                if (isNaN(itm.index)) {
                                                    tool.toast.error(`序号应为整数`)
                                                    return
                                                }
                                                if (itm.index < 1 || itm.index > paper.list.length) {
                                                    tool.toast.error(`序号范围：1~${paper.list.length}`)
                                                    return
                                                }
                                                if (itm.index !== e.item.item.index) {
                                                    paper.moveItem(e.item.item.index - 1, itm.index - 1)
                                                }
                                                store.hideFormDialog()
                                            }, true, () => store.hideFormDialog())
                                        }
                                        reloadPage()
                                    }
                                }
                            }
                        ]
                    })(),
                ]
            }
        }
    }

    return refresh
}